package org.wishwork.api.supplier.query;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wishwork.api.Api;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 供应商查询
 * @author: WangYX
 * @create: 2022-04-08 15:50
 * @Version: 1.0.0
 **/
public class SupplierQueryApi extends Api<List<SupplierQueryResponse>, SupplierQueryRequest> {

    private static final Logger log = LoggerFactory.getLogger(SupplierQueryApi.class);

    private Context context;

    public SupplierQueryApi(Context context) {
        this.context = context;
    }

    @Override
    protected String query(SupplierQueryRequest supplierQueryRequest) throws Exception {
        String url = "/open/supplier/query";
        Map<String, Object> params = new HashMap<>();
        if (supplierQueryRequest.getSupplierCodes() != null && supplierQueryRequest.getSupplierCodes().size() > 0) {
            params.put("supplier_codes", supplierQueryRequest.getSupplierCodes());
        }
        return HttpHelper.sendRequest(supplierQueryRequest,params, url);
    }

    @Override
    protected List<SupplierQueryResponse> process(JSONObject data, SupplierQueryRequest supplierQueryRequest) throws Exception {
        JSONArray datas = data.getJSONArray("datas");
        List<SupplierQueryResponse> supplierQueryResponses = datas.toJavaList(SupplierQueryResponse.class);
        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer pageIndex = supplierQueryRequest.getPageIndex();
            SupplierQueryRequest build = supplierQueryRequest.toBuilder().pageIndex(++pageIndex).build();
            List<SupplierQueryResponse> business = business(build);
            supplierQueryResponses.addAll(business);
        }
        return supplierQueryResponses;
    }
}
